//
//  NetworkHandler2.m
//  UI9_tableView+网络
//
//  Created by Marry W. on 15/12/31.
//  Copyright © 2015年 www.lanou39.蓝鸥科技. All rights reserved.
//

#import "NetworkHandler2.h"

@implementation NetworkHandler2

+(void)GETWithURL:(NSString *)str delegate:(id<PassDelegate2>)delegate
{
    // 中文转码
    NSString *urlStr = [str stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet characterSetWithCharactersInString:str]];
    // str -> url
    NSURL *url = [NSURL URLWithString:urlStr];
    // url->request
    // 参数1: url;
    // 参数2: 缓存;
    // 参数3: 超市限制;
    NSURLRequest *req = [NSURLRequest requestWithURL:url cachePolicy:(NSURLRequestUseProtocolCachePolicy) timeoutInterval:60];
    // session
    NSURLSession *session = [NSURLSession sharedSession];
    // task
    NSURLSessionDataTask *take = [session dataTaskWithRequest:req completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            // JSON解析中data 不能为nil
            if (error) {
                NSLog(@"错误信息: %@", error);
            }else{
                // JSON解析
                NSError *jError = nil;
                id result = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:&jError];
                if (jError) {
                    NSLog(@"解析错误: %@", jError);
                }else{
                    // 向外部JSON数据
                    [delegate passValue2:result];
                }
            }
        });
    }];
    [take resume];
    
}

@end
